#include<muduo/net/EventLoop.h>
#include<muduo/net/TcpServer.h>
#include<iostream>
#include<functional>
#include<unordered_map>
class DictServer
{
public:
  DictServer(int16_t port):_server(&_baseloop,muduo::net::InetAddress("0.0.0.0",port)
            ,"DictServer",muduo::net::TcpServer::Option::kReusePort)
  {
    //因为类内函数会自带this指针，通过bind可以让函数适应不同场景
    _server.setConnectionCallback(std::bind(&DictServer::onConnect,this,std::placeholders::_1));
    _server.setMessageCallback(std::bind(&DictServer::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
  }
  void Start()
  {
    _server.start();//启动服务
    _baseloop.loop();//开启事件监控，epoll
  }
  ~DictServer(){}
private:
  //对监听事件的回调函数
  void onConnect(const muduo::net::TcpConnectionPtr &conn)
  {
    if(conn->connected()==true)
    {
      std::cout<<"connect success\n";
    }
    else
    {
      std::cout<<"client quit\n";
    }
  }
  //处理请求
  std::string translate(std::string& word)
  {
    static std::unordered_map<std::string,std::string> dict=
    {
      {"Hello", "你好"}, 
      {"你好", "Hello"}, 
      {"World", "世界"}, 
      {"世界", "World"}
    };
    auto pos = dict.find(word);
    if(pos==dict.end())
    {
      return "null";
    }
    return pos->second;
  }
  //对io事件处理的回调函数
  void onMessage(const muduo::net::TcpConnectionPtr &conn,  
                muduo::net::Buffer *buf, 
                muduo::Timestamp t)
  {
    std::string message = buf->retrieveAllAsString();//获取需要进行处理的请求
    //对请求进行处理
    std::string rep = translate(message);
    //发送应答
    conn->send(rep);
  }
private:
  muduo::net::EventLoop _baseloop;
  muduo::net::TcpServer _server;
};

int main()
{
  DictServer server(8080);
  server.Start();
  return 0;
}
